package org.kust.bbs.admin.controller;

import org.kust.bbs.admin.service.IAdminService;
import org.kust.bbs.common.utils.JwtUtils;
import org.kust.bbs.common.web.JsonResult;
import org.kust.bbs.pojo.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 管理员登录
     *
     * @param admin
     * @return
     */
    @GetMapping("/login")
    public JsonResult<String> adminLogin(Admin admin) {
        String token = adminService.login(admin);
        redisTemplate.opsForValue().set(admin.getName(), token, 72, TimeUnit.HOURS);
        return JsonResult.ok(redisTemplate.opsForValue().get(admin.getName()));
    }

    /**
     * 前端解析出name(id),根据name(id)获取管理员信息
     *
     * @param request
     * @return
     */
    @GetMapping("/selectAdmin")
    public JsonResult<Admin> admin(HttpServletRequest request) {
        Integer id = JwtUtils.getNumberIdByJwtToken(request);
        return JsonResult.ok(adminService.selectAdmin(id));
    }

    /**
     * 管理员登出
     *
     * @param name
     * @return
     */
    @GetMapping("/logoff")
    public JsonResult<String> adminLogoff(String name) {
        redisTemplate.delete(name);
        return JsonResult.ok(redisTemplate.opsForValue().get(name));
    }
}
